package com.message.admin.send.task;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.message.admin.send.enums.SendStatus;
import com.message.admin.send.pojo.SendSms;
import com.message.admin.send.service.SendSmsService;
import com.system.comm.utils.FrameNoUtil;
import com.system.comm.utils.FrameSpringBeanUtil;
import com.system.handle.model.ResponseCode;
import com.system.handle.model.ResponseFrame;

/**
 * 启动线程3分钟更新一次配置文件
 * @author yuejing
 * @date 2016年10月22日 上午9:58:59
 * @version V1.0.0
 */
public class SendSmsTask {

	private static final Logger LOGGER = LoggerFactory.getLogger(SendSmsTask.class);

	private static final int WAIT_NUM = 20;

	public void run(int initialDelay, int period) {
		String servNo = FrameNoUtil.uuid();
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
		SendSmsService sendSmsService = FrameSpringBeanUtil.getBean(SendSmsService.class);
		Runnable runnable = new Runnable() {
			public void run() {
				try {
					//修改待发送的短信为当前服务的
					sendSmsService.updateWaitToIng(servNo, WAIT_NUM);
					List<SendSms> smss = sendSmsService.findIng(servNo);
					for (SendSms ss : smss) {
						//发送短信
						deal(ss);
					}
				} catch (Exception e) {
					LOGGER.error("处理邮件发送异常: " + e.getMessage(), e);
				}
			}
		};
		// 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间  
		service.scheduleAtFixedRate(runnable, initialDelay, period, TimeUnit.SECONDS);
	}

	private void deal(SendSms sendSms) {
		SendSmsService sendSmsService = FrameSpringBeanUtil.getBean(SendSmsService.class);
		//调用发送邮件的接口
		ResponseFrame seFrame = sendSms(sendSms);
		if(ResponseCode.SUCC.getCode() == seFrame.getCode().intValue()) {
			//发送成功
			sendSmsService.updateStatus(sendSms.getId(), SendStatus.SUCC.getCode());
			LOGGER.info("短信发送成功! 接收人[" + sendSms.getPhone() + "]");
		} else {
			//发送失败
			sendSmsService.updateStatus(sendSms.getId(), SendStatus.FAIL.getCode());
			LOGGER.info("短信发送失败! 接收人[" + sendSms.getPhone() + "]");
		}
	}

	private ResponseFrame sendSms(SendSms sendSms) {
		ResponseFrame frame = new ResponseFrame();
		//TODO 调用发送短信的功能

		frame.setSucc();
		return frame;
	}
}